<template>
  <div class="box">

    <section class="condition">
      <el-input placeholder="请输入内容"
                v-model="searchData.q"
                @keyup.enter.native="onSearch"
                class="input-with-select">
        <el-select v-model="searchData.pre" @change="handleChangeType" slot="prepend" placeholder="请选择">
          <el-option v-for="(item, index) in searchSelectData"
                     :key="index"
                     :label="item.dictLabel"
                     :value="item.dictValue"></el-option>
          <!--<el-option label="文书档案" value="文书档案"></el-option>
          <el-option label="会计档案" value="会计档案"></el-option>
          <el-option label="照片档案" value="照片档案"></el-option>
          <el-option label="实物档案" value="实物档案"></el-option>
          <el-option label="科技档案" value="科技档案"></el-option>-->
        </el-select>
        <!--<el-button slot="append" icon="el-icon-search"></el-button>-->
      </el-input>
      <el-button type="primary" @click="onSearch">搜索</el-button>
<!--      <el-button type="primary" @click="onSearch('keywordsearch')">全文检索</el-button>-->
    </section>

    <div class="content" id="content-box" ref="content">

      <div class="content-box">
        <!--搜索条件分组-->
        <search-condition :data="searchListData"
                          @change="handleChangeSearch"></search-condition>

        <div class="list-box">
          <div class="list-title" v-if="isSearchFlog">
            <div class="result" >
              <label>搜索结果</label>
              为您找到相关结果约<span>{{listInfo.total}}</span>个<!--，用时0.444秒-->
            </div>
            <div class="choice">
              <el-select v-model="sort"
                         placeholder="排序方式"
                         @change="handleSort"
                         size="small">
                <el-option
                  v-for="(item, index) in sortList"
                  :key="index"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
              <el-select v-model="lift"
                         @change="handleSortLift"
                         placeholder="搜索范围"
                         size="small">
                <el-option
                  v-for="(item, index) in searchRange"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>

          <div class="search-list-box infinite-list"
               v-infinite-scroll="load"
               infinite-scroll-disabled="disabled">

              <search-list v-for="(item, index) in listData"
                           :key="index"
                           :index="Number(index+1)"
                           :categoryAll="categoryAll"
                           :data="item"></search-list>
              <div class="empty" v-if="listData.length<1 && !loading">
                <span>暂无数据</span>
              </div>
              <p class="text-center" v-if="loading">加载中...</p>
              <p class="text-center" v-if="listData.length>0 && noMore">没有更多了</p>

          </div>

        </div>
      </div>

      <div class="btn-up" v-if="isShowUp" @click="handleToTop">
        <i class="el-icon-d-arrow-right"></i>
      </div>
    </div>

  </div>
</template>

<script>
import SearchCondition from './queryTemplate/searchCondition'
import SearchList from './queryTemplate/searchList'
import { mapActions } from 'vuex'
import { getUtilizeQueryList } from '../../../api/utilize/utilizeQuery'
import { mapFields } from 'vuex-map-fields'
import { getArchivesDicId, getSysDicId } from '../../../api/dictionary/dictionary'

export default {
  name: 'UtilizeQuery',
  components: {
    SearchList,
    SearchCondition
  },
  data () {
    return {
      searchSelectData: [], // 搜索
      isShowUp: false, // 回到顶部
      loading: false,
      listInfo: {}, // 列表信息
      listData: [],
      searchListData: [], // 搜索条件
      lift: true, // 升降序
      sort: '', // 选择排序方式
      searchData: {
        pageNo: 1,
        pageSize: 20,
        total: '',
        chinesePre: '', // 中文名
        q: '', // 值
        pre: '', // 前置条件
        facetQuery: [], // 分片过滤参数
        params: [],
        sorters: [] // 排序
      },
      sortList: [],
      searchRange: [{
        label: '升序',
        value: true
      }, {
        label: '降序',
        value: false
      }],
      isSearch: false,
      isSearchFlog: false
    }
  },
  activated () {
    // isUseCache为false时才重新刷新获取数据
    // 因为对list使用keep-alive来缓存组件，所以默认是会使用缓存数据的
    document.getElementById('content-box').scrollTop = sessionStorage.getItem('contentBoxScrollTop')
  },
  beforeRouteLeave (to, from, next) {
    from.meta.keepAlive = to.path === '/utilize/utilizeQuery/utilizeDetails'
    next()
  },
  mounted () {
    this.getCategoryAll()
    this.getDic()
    // 默认收起左侧导航栏
    this.setNavNarrow(true)
    this.$refs.content.addEventListener('scroll', this.scrollToTop)
  },
  destroyed () {
    window.removeEventListener('scroll', this.scrollToTop)
  },
  computed: {
    ...mapFields('currencyDic/getCategoryAll', {
      categoryAll: 'retrieved' // 所有门类
    }),
    noMore () {
      return this.listData.length >= this.searchData.total
    },
    disabled () {
      return this.loading || this.noMore
    }
  },
  methods: {
    ...mapActions('profile/navNarrow', ['setNavNarrow']),
    ...mapActions('currencyDic/getCategoryAll', ['getCategoryAll']),
    getDic () {
      getSysDicId('utilize_type').then(res => {
        this.searchSelectData = res.data.data
        this.searchData.pre = this.searchSelectData[0].dictValue
        this.searchData.chinesePre = this.searchSelectData[0].dictLabel
      })
      // 排序
      getArchivesDicId('utilize_sort').then(res => {
        this.sortList = res.data.data
        // 排序默认选中第一条
        this.searchData.sorters = [{
          asc: true,
          name: this.sortList[0].dictValue
        }]
        this.sort = this.sortList[0].dictValue
      })
    },
    handleSort (val) {
      this.searchData.sorters = [{
        asc: true,
        name: val
      }]
      this.handleSearch()
    },
    handleSortLift (val) {
      // 升降序
      this.searchData.sorters[0].asc = val
      this.handleSearch()
    },
    handleChangeType (val) {
      this.searchSelectData.map(item => {
        if (item.dictValue === val) {
          this.searchData.chinesePre = item.dictLabel
        }
      })
    },
    onSearch () {
      if (!this.searchData.q) {
        this.$message.warning('请填写搜索值！')
        return
      }
      delete this.searchData.facetQuery
      this.handleSearch()
    },
    handleSearch () {
      this.isSearch = false
      this.searchData.pageNo = 1
      this.listData = []
      this.loading = true
      this.getList()
    },
    handleChangeSearch (val) {
      // 选中搜索
      this.searchData.facetQuery = []
      Object.keys(val).forEach(key => {
        if (val[key].length > 0) {
          this.searchData.facetQuery.push({
            name: key,
            op: 'in',
            values: val[key]
          })
        }
      })
      this.handleSearch()
    },
    async load () {
      if (this.isSearch && this.searchData.q) {
        this.searchData.pageNo += 1
        await this.getList()
      }
    },
    getList () {
      this.isSearch = false
      this.isSearchFlog = true
      return getUtilizeQueryList(this.searchData).then(res => {
        this.listInfo = res.data.data.displayContent
        this.listData = this.listData.concat(res.data.data.displayContent.records)
        this.isSearch = this.listData.length < Number(res.data.data.displayContent.total)
        this.searchData.total = res.data.data.displayContent.total

        this.searchListData = res.data.data.facetContent
        this.loading = false
      }).catch(() => {
        this.isSearch = false
        this.loading = false
      })
    },
    // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop () {
      const scrollTop = document.getElementById('content-box').scrollTop
      this.isShowUp = scrollTop > 200
      sessionStorage.setItem('contentBoxScrollTop', scrollTop)
    },
    handleToTop () {
      // 回到顶部
      const timeTop = setInterval(() => {
        const top = document.getElementById('content-box').scrollTop
        const ispeed = Math.floor(-top / 5)
        document.getElementById('content-box').scrollTop = top + ispeed
        if (top <= 0) {
          clearInterval(timeTop)
        }
      }, 10)
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "../../../styles/mixin";

  .box {
    height: 100%;

    .condition {
      @include fj(flex-start);
      align-items: center;
      width: 80%;
      min-width: 1000px;
      margin: 0 auto;

      .input-with-select {
        margin-right: 15px;
        width: 400px;
      }

      ::v-deep .el-input-group__prepend {
        width: 120px;
      }
    }

    .content {
      height: calc(100% - 45px);
      overflow-y: auto;
      margin-top: 10px;
      margin-right: -20px;
      padding-right: 20px;

      .content-box {
        min-width: 1000px;
        width: 80%;
        margin: 0 auto;
      }

      .list-title {
        @include fj;
        align-items: center;
        padding: 10px 15px;
        background: #fff;

        .result {
          color: #999;
          font-size: 13px;

          label {
            font-weight: bolder;
            color: #333;
          }
        }

        .choice {
          ::v-deep .el-select {
            width: 120px;
            margin-left: 10px;
          }
        }
      }

      .btn-up {
        position: fixed;
        bottom: 50px;
        right: 50px;
        z-index: 10;
        cursor: pointer;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 100%;
        @include wh(40px, 40px);
        @include sc(26px, #FFF);
        text-align: center;
        line-height: 40px;

        i {
          transform: rotate(-90deg);
          margin-left: 2px;
        }

        &:hover {
          color: #409EFF;
          opacity: 0.7;
        }
      }
    }
  }

  .loading {
    height: 500px;
  }

  .empty {
    text-align: center;
    padding-top: 35px;
  }

  .search-list-box {
  }
</style>
